// pages/bluetooth-operator/bluetooth-operator.js

const dialog = require('../../utils/dialog.js')
const util = require('../../utils/util.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        device: {
            name:"test",
            device_id: 'aaaaaaaaa',
            device_uuid: 'bbbbbbbbbbbbbbbb',
            device_rssi: 56
        },
        services:[
            {
                uuid: 'AAAAAAA',
                isPrimary: true,
                characteristics:[
                    {
                        uuid: 'AAAAAA-001',
                        read: true,
                        write: true,
                        notify: true,
                        data: null
                    },
                    {
                        uuid: 'AAAAAA-002',
                        read: true,
                        write: true,
                        notify: true,
                        data: null
                    }
                ]
            },
            {
                uuid: 'BBBBBBB',
                isPrimary: true,
                characteristics:[
                    {
                        uuid: 'BBBBBBB-001',
                        read: true,
                        write: true,
                        notify: true,
                        data: null
                    },
                    {
                        uuid: 'BBBBBBB-002',
                        read: true,
                        write: true,
                        notify: true,
                        data: null
                    }
                ]
            }
        ]
    },

    //#region 页面生命周期函数

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log("Page onLoad...");

        this.setData({
            device: null,
            services:[]
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        console.log("Page onReady...");
        if(this.initDevice()) {
            this.initService();
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        console.log("Page onShow...")
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        console.log("Page onHide...");
       


    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        console.log("Page onUnload...");

        let device = this.data.device;

        wx.closeBLEConnection({
          deviceId: device.device_id,
          success: (res)=> {
            console.log("断开蓝牙连接成功...",res)
          }
        });
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        console.log("Page onPullDownRefresh...")
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        console.log("Page onReachBottom...")
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    //#endregion

    //#region 页面事件

    onReadCharacteristicValue(e) {
        try{
            let index_service = e.currentTarget.dataset.sidx;
            let index_characteristic = e.currentTarget.dataset.cidx;
            let service = this.data.services[index_service];
            let device = this.data.device;
            if(service) {
                let characteristic = service.characteristics[index_characteristic];
                if(characteristic) {
                    if(characteristic.properties.read) {
                        wx.readBLECharacteristicValue({
                            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                            deviceId:device.device_id,
                            // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                            serviceId: service.uuid,
                            // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
                            characteristicId: characteristic.uuid,
                            success: (res)=> {
                              console.log('readBLECharacteristicValue:', res)
                            }
                        });
                    } else {
                        dialog.msg('该属性没有读取数据权限！');
                    }
                } else {
                    console.log('该索引找不到对应的Characteristic', index_characteristic);
                    dialog.error('找不到对应的Characteristic');
                }
            } else {
                console.log('该索引找不到对应的Service', index_service);
                dialog.error('找不到对应的Service');      
            }
        }catch(e) {
            console.error(e);
        }
    },

    onWriteCharacteristicValue(e) {
        try{
            let index_service = e.currentTarget.dataset.sidx;
            let index_characteristic = e.currentTarget.dataset.cidx;
            let service = this.data.services[index_service];
            let device = this.data.device;
            if(service)  {
                let characteristic = service.characteristics[index_characteristic];
                if(characteristic) {
                    if(characteristic.properties.write) {
                        dialog.input('请输入数据','请输入数据', (data)=>{
                            let buffer = util.string2buffer(data);
                            console.log(buffer);
                            wx.writeBLECharacteristicValue({
                                // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
                                deviceId: device.device_id,
                                // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                                serviceId: service.uuid,
                                // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
                                characteristicId : characteristic.uuid,
                                // 这里的 value 是ArrayBuffer类型
                                value: buffer,
                                success: (res) => {
                                  console.log('writeBLECharacteristicValue success', res);
                                }
                            });
                        });
                        
                    } else {
                        dialog.msg('该属性没有写入数据权限！');
                    }
                } else {
                    console.log('该索引找不到对应的Characteristic', index_characteristic);
                    dialog.error('找不到对应的Characteristic');
                }
            } else {
                console.log('该索引找不到对应的Service', index_service);
                dialog.error('找不到对应的Service');      
            }
        }catch(e) {
            console.error(e);
        }
    },
    //#endregion

    //#region  私有方法

    initDevice() {
        try{
            let app = getApp();
            let di = app.globalData.deviceInfo;
            console.log(di);
            if(di) {
                this.setData({
                    device: {
                        name : di.name,
                        device_id : di.device_id,
                        device_uuid: di.device_uuid,
                        device_rssi: di.device_rssi
                    }
                });
                return true;
            } else {
                return false;
            }
           
        } catch(e) {
            console.log("加载蓝牙信息异常！", e);
            return false;
        }
    },

    initService() {
        try{
            wx.showLoading({
              title: '正在连接蓝牙...',
            });
            let device = this.data.device;
            let _this = this;

            wx.onBLECharacteristicValueChange(function(characteristic) {
                console.log('characteristic value comed:', characteristic);
                let services = _this.data.services;
                let service = services.find((curVal, index)=>{
                    return curVal.uuid == characteristic.serviceId;
                });
                if(service) {
                    let c = service.characteristics.find((curVal, index) =>{
                        return curVal.uuid == characteristic.characteristicId;
                    });

                    if(c) {
                        c["data"] = util.ab2hex(characteristic.value);
                        _this.setData({
                            services: services
                        });
                    }
                }
            });

            let loadCharacteristicsInfo = (services) => {
                let s1 = services.pop();
                if(s1) {
                    wx.getBLEDeviceCharacteristics({
                        deviceId: device.device_id,
                        serviceId: s1.uuid,
                        success: (res) => {
                            console.log("getBLEDeviceCharacteristics success.", res);
                            let s = _this.data.services;
                            let v = s.find((cur, index,) => {
                                return cur.uuid == s1.uuid;
                            });
                            if(v) {
                                v["characteristics"] = [];
                                v["characteristics"].push(...res.characteristics);
                            }
                            _this.setData({
                                services: s
                            });
                        },
                        fail: (res) => {
                            console.log("getBLEDeviceCharacteristics fail.", res);
                        },
                        complete: (res) => {
                            loadCharacteristicsInfo(services);
                        }
                    });
    
                } else {
                    wx.hideLoading({
                        success: (res) => {},
                    });
                }
            }

            let loadServiceInfo = () =>{
                wx.getBLEDeviceServices({
                    deviceId:device.device_id,
                    success:(res) => {
                        console.log("getBLEDeviceServices success.",res);
                        let services = [];
                        for(let i =0; i< res.services.length; i++) {
                            services.push(res.services[i]);
                        }
                        _this.setData({
                            services: services
                        });
                        let tmp = [...services];
                        loadCharacteristicsInfo(tmp);
                    },
                    fail: (res) => {
                        console.log("getBLEDeviceServices fail.",res);
                    },
                });
            };

            let conn = false;
            wx.createBLEConnection({
                deviceId: device.device_id,
                timeout: 1000 * 10,
                success: (res) => {
                    console.log("createBLEConnection success.",res);
                    conn = true;
                    loadServiceInfo();
                },
                fail: (res) => {
                    console.log("createBLEConnection fail.",res);
                    if(res.errno == 1509007) {
                        conn = true;
                        loadServiceInfo();
                    }
                },
                complete:(res)=> {
                    if(!conn) {
                        wx.hideLoading({
                            success: (res) => {},
                        });
                    }
                }
            });
        }catch(e) {
            console.log("初始化蓝牙服务信息异常!",e);
        }
    },

    ////#endregion
})